'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { 
  getTabToken, 
  setTabToken, 
  clearTabToken, 
  hasValidTabToken, 
  getAllActiveTokens, 
  hasValidTabTokenEnhanced,
  persistTabToken,
  restorePersistentToken
} from '@/lib/cache'
import { useAuth } from '@/contexts/AuthContext'

export default function TestTokenPage() {
  const { user, isAuthenticated, isLoading } = useAuth()
  const [tokenInfo, setTokenInfo] = useState<any>({})
  const [testResults, setTestResults] = useState<any>({})

  // 更新token信息显示
  const updateTokenInfo = () => {
    try {
      const currentToken = getTabToken()
      const isValid = hasValidTabToken()
      const isValidEnhanced = hasValidTabTokenEnhanced()
      const allTokens = getAllActiveTokens()
      
      setTokenInfo({
        currentToken: currentToken ? `${currentToken.substring(0, 20)}...` : '无',
        isValid,
        isValidEnhanced,
        allTokensCount: allTokens.length,
        allTokens: allTokens.map(t => ({
          tabId: t.tabId,
          token: `${t.token.substring(0, 20)}...`,
          lastActivity: new Date(t.lastActivity).toLocaleString()
        }))
      })
    } catch (error) {
      console.error('获取token信息失败:', error)
    }
  }

  useEffect(() => {
    updateTokenInfo()
    // 定期更新token信息
    const interval = setInterval(updateTokenInfo, 5000)
    return () => clearInterval(interval)
  }, [])

  // 测试token功能
  const runTokenTests = async () => {
    const results: any = {}
    
    try {
      // 测试1: 设置测试token
      console.log('🧪 测试1: 设置测试token')
      const testToken = `test_token_${Date.now()}`
      setTabToken(testToken)
      results.setToken = { success: true, message: '测试token设置成功' }
    } catch (error: any) {
      results.setToken = { success: false, error: error.message }
    }

    try {
      // 测试2: 验证token
      console.log('🧪 测试2: 验证token')
      const isValid = hasValidTabToken()
      results.validateToken = { success: true, isValid, message: 'token验证完成' }
    } catch (error: any) {
      results.validateToken = { success: false, error: error.message }
    }

    try {
      // 测试3: 持久化token
      console.log('🧪 测试3: 持久化token')
      persistTabToken()
      results.persistToken = { success: true, message: 'token持久化成功' }
    } catch (error: any) {
      results.persistToken = { success: false, error: error.message }
    }

    try {
      // 测试4: 恢复持久化token
      console.log('🧪 测试4: 恢复持久化token')
      const restoredToken = restorePersistentToken()
      results.restoreToken = { 
        success: true, 
        restored: !!restoredToken,
        message: restoredToken ? '持久化token恢复成功' : '没有持久化token'
      }
    } catch (error: any) {
      results.restoreToken = { success: false, error: error.message }
    }

    try {
      // 测试5: 清理测试token
      console.log('🧪 测试5: 清理测试token')
      clearTabToken()
      results.clearToken = { success: true, message: '测试token清理成功' }
    } catch (error: any) {
      results.clearToken = { success: false, error: error.message }
    }

    setTestResults(results)
    updateTokenInfo()
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">Token 系统测试</h1>
        <Button onClick={runTokenTests} variant="outline">
          运行测试
        </Button>
      </div>

      {/* 认证状态 */}
      <Card>
        <CardHeader>
          <CardTitle>🔐 认证状态</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          <div className="flex items-center space-x-2">
            <span>状态:</span>
            <Badge variant={isAuthenticated ? "default" : "secondary"}>
              {isLoading ? "加载中..." : isAuthenticated ? "已认证" : "未认证"}
            </Badge>
          </div>
          {user && (
            <div className="text-sm text-muted-foreground">
              用户: {user.username} ({user.role})
            </div>
          )}
        </CardContent>
      </Card>

      {/* Token 信息 */}
      <Card>
        <CardHeader>
          <CardTitle>🔑 Token 信息</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <span className="font-medium">当前Token:</span>
              <div className="text-sm text-muted-foreground font-mono">
                {tokenInfo.currentToken || '无'}
              </div>
            </div>
            <div>
              <span className="font-medium">有效性:</span>
              <div className="flex space-x-2">
                <Badge variant={tokenInfo.isValid ? "default" : "secondary"}>
                  {tokenInfo.isValid ? "有效" : "无效"}
                </Badge>
                <Badge variant={tokenInfo.isValidEnhanced ? "default" : "secondary"}>
                  {tokenInfo.isValidEnhanced ? "增强有效" : "增强无效"}
                </Badge>
              </div>
            </div>
          </div>
          
          <div>
            <span className="font-medium">活跃标签页数量:</span>
            <Badge variant="outline" className="ml-2">
              {tokenInfo.allTokensCount || 0}
            </Badge>
          </div>

          {tokenInfo.allTokens && tokenInfo.allTokens.length > 0 && (
            <div>
              <span className="font-medium">活跃标签页:</span>
              <div className="mt-2 space-y-2">
                {tokenInfo.allTokens.map((tab: any, index: number) => (
                  <div key={index} className="text-sm bg-muted p-2 rounded">
                    <div>标签页ID: {tab.tabId}</div>
                    <div>Token: {tab.token}</div>
                    <div>最后活动: {tab.lastActivity}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 测试结果 */}
      {Object.keys(testResults).length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>🧪 测试结果</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {Object.entries(testResults).map(([testName, result]: [string, any]) => (
                <div key={testName} className="border rounded p-3">
                  <div className="flex items-center justify-between">
                    <span className="font-medium capitalize">{testName}</span>
                    <Badge variant={result.success ? "default" : "destructive"}>
                      {result.success ? "成功" : "失败"}
                    </Badge>
                  </div>
                  <div className="text-sm text-muted-foreground mt-1">
                    {result.message || result.error}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 操作按钮 */}
      <Card>
        <CardHeader>
          <CardTitle>⚙️ 操作</CardTitle>
        </CardHeader>
        <CardContent className="space-x-2">
          <Button onClick={() => updateTokenInfo()} variant="outline">
            刷新Token信息
          </Button>
          <Button onClick={() => setTabToken(`manual_token_${Date.now()}`)} variant="outline">
            设置手动Token
          </Button>
          <Button onClick={() => clearTabToken()} variant="outline">
            清理当前Token
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
